use serde_derive::Deserialize;
use std::{collections::HashMap, path::Path};

#[derive(Debug)]
pub struct MachineConfig {
    /// 生产商
    pub manufacture: String,
    /// Cpu构架
    pub arch: String,
    /// 特性支持features
    pub features: Vec<String>,
}

impl MachineConfig {
    /// 从config/machine_features.toml选择出指定硬件的配置信息
    pub fn select(hardware: impl AsRef<str>) -> Option<Self> {
        // 平台对应好多硬件， 硬件下面对应好多配置
        type ConfigFile = HashMap<String, HashMap<String, RawHardwareConfig>>;

        #[derive(Deserialize, Debug)]
        struct RawHardwareConfig {
            arch: String,
            features: Option<Vec<String>>,
        }

        let file = Path::new(std::env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .join("config")
            .join("machine_features.toml");
        let file = std::fs::read_to_string(file).unwrap();
        let config = toml::from_str::<ConfigFile>(&file).unwrap();
        for (manufacture, products) in config {
            for (hard, raw) in products {
                if hard == hardware.as_ref() {
                    return Some(Self {
                        manufacture,
                        arch: raw.arch,
                        features: raw.features.unwrap_or_default(),
                    });
                }
            }
        }
        None
    }
}
